package com.njh.charges.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hos.entity.his.CareOrderItem;
import com.hos.entity.his.OrderCharge;
import com.hos.entity.his.OrderChargeItem;
import com.hos.entity.sys.User;
import com.hos.utils.IdGeneratorUtil;
import com.hos.utils.WebUtil;
import com.njh.charges.feigns.UserFeign;
import com.njh.charges.mapper.*;
import com.njh.charges.service.ChargeService;
import com.njh.charges.vo.AllOrderChargeVo;
import com.njh.charges.vo.OrderChargeDtoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author ：njh
 * @date ：Created in 2023/12/14 11:39
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class ChargeServiceImpl implements ChargeService {

    @Resource
    private OrderChargeDtoVoMapper orderChargeDtoVoMapper;
    @Resource
    private OrderChargeMapper orderChargeMapper;
    @Resource
    private OrderChargeItemMapper orderChargeItemMapper;
    @Resource
    private UserFeign userFeign;
    @Resource
    private CareOrderVoMapper careOrderVoMapper;
    @Resource
    private CareOrderItemMapper careOrderItemMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Boolean createOrderChargeWithCash(OrderChargeDtoVo orderChargeDtoVo) {

        //根据item_id修改his_care_order_item的status
        //新建his_order_charge（订单）    ch_id,reg_id不变  自创order_id
        //新建his_order_charge_item(订单详情)     co_id直接拿    order_id如上    自创item_id（每个都不一样）


        String OrderId = IdGeneratorUtil.nextId("ODC");
        Double sum = 0D;

        for (OrderChargeItem c :
                orderChargeDtoVo.getOrderChargeItemDtoList()) {

            sum += c.getItemAmount().doubleValue();

            UpdateWrapper<CareOrderItem> wrapper = new UpdateWrapper();
            wrapper.lambda()
                    .set(CareOrderItem::getStatus, 1)
                    .eq(CareOrderItem::getItemId, c.getItemId());
            careOrderItemMapper.update(wrapper);


//根据itemid查询OrderChargeItem表，如果存在则修改现有的表，没有则新增
            QueryWrapper<OrderChargeItem> queryWrapper=new QueryWrapper();
            queryWrapper.lambda()
                    .eq(OrderChargeItem::getItemId,c.getItemId());
            OrderChargeItem orderChargeItem1 = orderChargeItemMapper.selectOne(queryWrapper);
            if(orderChargeItem1==null){
                //新建his_order_charge_item(订单详情)     co_id直接拿    order_id如上    自创item_id（每个都不一样）
                OrderChargeItem orderChargeItem=new OrderChargeItem();
                orderChargeItem.setItemId(c.getItemId());
                orderChargeItem.setCoId(c.getCoId());
                orderChargeItem.setItemName(c.getItemName());
                orderChargeItem.setItemPrice(c.getItemPrice());
                orderChargeItem.setItemNum(c.getItemNum());
                orderChargeItem.setItemAmount(c.getItemAmount());
                orderChargeItem.setOrderId(OrderId);
                orderChargeItem.setItemType(c.getItemType());
                orderChargeItem.setStatus("1");
                orderChargeItemMapper.insert(orderChargeItem);
            }else{
                //存在订单则修改旧订单信息
                //修改his_order_charge_item(订单详情) 的订单号orderid
                UpdateWrapper<OrderChargeItem> wrapper2=new UpdateWrapper();
                wrapper2.lambda()
                        .set(OrderChargeItem::getOrderId,OrderId)
                        .set(OrderChargeItem::getStatus,1)
                        .eq(OrderChargeItem::getItemId,c.getItemId());
                orderChargeItemMapper.update(wrapper2);
            }

        }

        //新建his_order_charge（订单）    ch_id,reg_id不变  自创order_id
        OrderCharge orderCharge = new OrderCharge();
        orderCharge.setOrderId(OrderId);
        orderCharge.setOrderAmount(BigDecimal.valueOf(sum));
        orderCharge.setChId(orderChargeDtoVo.getOrderChargeDto().getChId());
        orderCharge.setRegId(orderChargeDtoVo.getOrderChargeDto().getRegId());
        orderCharge.setPatientName(orderChargeDtoVo.getOrderChargeDto().getPatientName());
        orderCharge.setOrderStatus("1");
        orderCharge.setPayPlatformId(null);
        orderCharge.setPayTime(new Date());
        orderCharge.setPayType("0");
        orderCharge.setCreateTime(new Date());
        orderCharge.setUpdateTime(null);
        orderCharge.setCreateBy(getUserByToken().getUserName());
        orderCharge.setUpdateBy(null);
        orderChargeMapper.insert(orderCharge);


//GH1702864141205459448

        //前端返回数据
//        Object { orderChargeDto: {…}, orderChargeItemDtoList: (1) […] }
//        orderChargeDto: Object { orderAmount: 20, chId: "1", regId: "1", … }
//        chId: "1"
//        orderAmount: 20
//        patientName: "张三"
//        regId: "1"
//
//        orderChargeItemDtoList: Array [ {…} ]
//        0: Object { itemId: "100", coId: "1", itemName: "脑心通", … }
//        coId: "1"
//        itemAmount: 20
//        itemId: "100"
//        itemName: "脑心通"
//        itemNum: 2
//        itemPrice: 20
//        itemType: "1"


        return null;
    }

    @Override
    public Page<OrderCharge> queryAllOrderChargeForPage(AllOrderChargeVo allOrderChargeVo) {
        // 设置分页参数
        Page<OrderCharge> page = new Page<>(allOrderChargeVo.getPageNum(), allOrderChargeVo.getPageSize());

        LambdaQueryWrapper<OrderCharge> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(OrderCharge::getCreateTime);
        // 进行条件查询
        if (StringUtils.hasText(allOrderChargeVo.getPatientName())) {
            wrapper.like(OrderCharge::getPatientName, allOrderChargeVo.getPatientName());
        }
        if (StringUtils.hasText(allOrderChargeVo.getRegId())) {
            wrapper.eq(OrderCharge::getRegId, allOrderChargeVo.getRegId());
        }

        return this.orderChargeMapper.selectPage(page, wrapper);
    }

    @Override
    public List<OrderChargeItem> queryOrderChargeItemByOrderId(String orderId) {

        LambdaQueryWrapper<OrderChargeItem> wrapper = new LambdaQueryWrapper<>();
        // 进行条件查询
        if (StringUtils.hasText(orderId)) {
            wrapper.eq(OrderChargeItem::getOrderId, orderId);
        }

        return this.orderChargeItemMapper.selectList(wrapper);
    }

    @Override
    public int payWithCash(String orderId) {

        UpdateWrapper<OrderCharge> wrapper = new UpdateWrapper();
        wrapper.lambda()
                .set(OrderCharge::getOrderStatus, 1)
                .set(OrderCharge::getPayTime, new Date())
                .set(OrderCharge::getPayType, 0)
                .set(OrderCharge::getUpdateTime, new Date())
                .set(OrderCharge::getUpdateBy, getUserByToken().getUserName())
                .eq(OrderCharge::getOrderId, orderId);
        int update = orderChargeMapper.update(wrapper);

        //根据orderid查询订单的所有子项
        QueryWrapper<OrderChargeItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(OrderChargeItem::getOrderId, orderId);
        List<OrderChargeItem> orderChargeItems = orderChargeItemMapper.selectList(queryWrapper);

        for (OrderChargeItem c :
                orderChargeItems) {

            //根据item_id修改his_care_order_item的status
            UpdateWrapper<CareOrderItem> wrapper2 = new UpdateWrapper();
            wrapper2.lambda()
                    .set(CareOrderItem::getStatus, 1)
                    .eq(CareOrderItem::getItemId, c.getItemId());
            careOrderItemMapper.update(wrapper2);

            //修改his_order_charge_item(订单详情)    修改status
            UpdateWrapper<OrderChargeItem> wrapper3 = new UpdateWrapper();
            wrapper3.lambda()
                    .set(OrderChargeItem::getStatus, 1)
                    .eq(OrderChargeItem::getItemId, c.getItemId());
            orderChargeItemMapper.update(wrapper3);
        }


        return update;
    }


    /**
     * @return com.hos.entity.sys.User
     * @create by: 陈海彬
     * @description: 获取请求用户的信息
     * @create time: 2023/12/12 10:39
     */
    private User getUserByToken() {
        String token = WebUtil.getToken();
        String phone = redisTemplate.opsForValue().get("user:" + token);
        return userFeign.selectUserByPhone(phone);
    }
}